package proxypattern.impl;

import lombok.Getter;
import proxypattern.base.BaseState;
import proxypattern.entity.RemoteGumballMachine;

import java.rmi.RemoteException;
import java.util.Random;

/**
 * 糖果机已接收25美分状态
 * @author yaojianfeng
 */
public class HasQuarterStateImpl implements BaseState {
    @Getter
    private String desc = "已接受25美分硬币";
    /**
     * 新需求 增加一个随机数生成器,产生10%赢的机会
     */
    Random randomWinner = new Random(System.currentTimeMillis());
    private transient RemoteGumballMachine gumballMachine;

    /**
     * 我们通过构造器得到糖果机的引用,然后将它记录在实例变量中
     * @param gumballMachine 糖果机对象
     */
    public HasQuarterStateImpl(RemoteGumballMachine gumballMachine) {
        this.gumballMachine = gumballMachine;
    }


    @Override
    public void insertQuarter() {
        System.out.println("虽然你想多投 但是老子不接受 o(￣ヘ￣o＃)!");
    }

    /**
     * 退出顾客的25美分
     * 将状态转换到noQuarterState状态
     */
    @Override
    public void ejectQuarter() {
        System.out.println("给你退25美分  欢迎下次再来啊");
        gumballMachine.setState(gumballMachine.getNoQuarterState());
    }

    @Override
    public void turnCrank() {
        System.out.println("曲柄被转动 命运的大门已经打开 准备接受糖果吧!");
        //产生0-9十个随机数字 然后决定这个顾客是否赢了
        int winner  = randomWinner.nextInt(10);
        //如果赢了 而且有足够的糖果可以一次得到两颗的话,我们就进入winnerState状态
        try {
            if (winner == 0 && (gumballMachine.getCount()>1)){
                gumballMachine.setState(gumballMachine.getWinnerState());
            }else {
            //否则将状态转换为售出状态   注意:状态是状态  行为是行为 不能混为一谈
            gumballMachine.setState(gumballMachine.getSoldState());
            }
        } catch (RemoteException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void dispense() {
        System.out.println("糖果已售出!");
    }
}
